package tjs.org.springLoader.reloader;

import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;

/**
 * Created by Nicky.Tang on 2021/9/30 9:53 上午
 *
 * @since 02.12.10
 */
public class ChangeClassReloaderOld {

    private ApplicationContext applicationContext;
    private ClassLoader classLoader;
    private Method doDefineClass;

    public ChangeClassReloaderOld(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        //findDefineClassMethods();
    }

    private void findDefineClassMethods() {
        try {

            Class<?> classLoaderClass = null;
            Class<?> parent = this.classLoader.getClass();
            while(parent.getSuperclass()!=null){
                if(parent.getSuperclass().equals(ClassLoader.class)){
                    classLoaderClass = parent.getSuperclass();
                    break;
                }
                parent=parent.getSuperclass();
            }
            this.doDefineClass = classLoaderClass.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class, ProtectionDomain.class);
            this.doDefineClass.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public Class<?> defineClass(String beanClassName, byte[] newClassBytes) {
        try {
            return (Class<?>) doDefineClass.invoke(this.classLoader, beanClassName, newClassBytes, 0, newClassBytes.length, null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
